import { connection } from '../app/database/mysql';
import { getInfoByIdAndType } from '../corner/common.service';
import { menuModel } from './mainPage.model';

/**
 * 获取用户统计
 */
export const getUser = async () => {
  // 准备查询
  const statement = `
    SELECT COUNT(*) as user_total from users
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data;
}

/**
 * 获取统计待审核
 */
export const getPending = async (status: number) => {
  // 准备查询
  let statement = `
    SELECT * from tb_index
    WHERE status = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, status);

  let totalStatement = `SELECT FOUND_ROWS() as total`;
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total

  let arr = []
  for (let item of data as any) {
    let res = await getInfoByIdAndType(item.target_id, item.type)
    if (!res) continue;
    item.data = res;
    arr.push(item);
  }

  let res = {
    arr,
    totalCount
  };

  // 提供数据
  return res;
}

/**
 * 获取菜单
 */
export const getMenu = async (admin_id: number) => {
  let adminAuth = `SELECT menu_id from authority_management where admin_id = ${admin_id}`
  const [result] = await connection.promise().query(adminAuth)
  let mId: any;
  if (result[0] && result[0].menu_id) {
    mId = result[0].menu_id
  }
  
  if (!mId) {
    return {msg: '出现错误'}
  }

  // 准备查询
  let statement = `SELECT * FROM menu WHERE id IN (${mId})`;

  // 执行查询
  const [data] = await connection.promise().query(statement);
  
  let menuList = data;
  let formattedMenuList = [];

  for(let menu of menuList as any) {
    let subMenus = [];
    for (let subMenu of menuList as any) {
      let btnMenus = [];
      for (let btnMenu of menuList as any) {
        if (subMenu.id == btnMenu.parent_id) {
          btnMenus.push(btnMenu)
        }
      }
      subMenu['children'] = btnMenus;
      if (menu.id == subMenu.parent_id) {
        subMenus.push(subMenus)
      }
    };

    menu['children'] = subMenus
    if (menu.parent_id == 0){
      formattedMenuList.push(menu);
    }
  }

  // 提供数据
  return {
    formattedMenuList
  };
}

/**
 * 创建内容
 */
export const createAuthority = async (post: menuModel) => {
  // 准备查询
  const statement = `
    INSERT INTO authority_management
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateAuthority = async (post: menuModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE authority_management
    SET ?
    WHERE admin_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}
